<?php

class Controller
{
	/**
	 * Minden akció a modules/modulNev/akcioAction.php-ban
	 */
	const ACTION_PATH="modules/%s/%sAction.php";
	
	/**
	 * Osztálynévkonvenció:
	 * Action_ModulNevAkcioNeve (CamelCase)
	 */
	const ACTION_CLASS="Action_%s%s";
	
	const VIEW_PATH="modules/%s/%sView.php";
	const VIEW_CLASS="View_%s%s";
	
	/**
	 * Sablonok a modules/modulNev/templates/sablonNev.php-ban
	 */
	const TEMPLATE_PATH="modules/%s/template/%s.php";
	
	public static function init()
	{
		self::requireFile("lib/autoload.php");
		spl_autoload_register("Autoload::load");
		Request::init();
		User::init();
	}
	public static function run()
	{
		/**
		 * MVC
		 * 1. routing
		 * 2. akció végrehajtása
		 * 3. kimenet megjelenítése
		 */
		try
		{
			$action=self::getAction();
			$action->perform();
			$view=self::getView();
			$view->show();
		}
		catch(Exception $e)
		{
			echo "Bocs, valami nagy gubanc történt, próbálkozz később... (".$e->getMessage().")";
		}
	}
	public static function getAction()
	{
		$requestModule=Request::getRequestModule();
		$requestAction=Request::getRequestAction();
		$path=self::getActionPath($requestModule, $requestAction);
		$class=self::getActionClass($requestModule, $requestAction);
		self::requireFile($path);
		return new $class;
	}
	public static function getView()
	{
		$requestModule=Request::getRequestModule();
		$requestAction=Request::getRequestAction();
		$path=self::getViewPath($requestModule, $requestAction);
		$class=self::getViewClass($requestModule, $requestAction);
		self::requireFile($path);
		return new $class;
	}
	public static function getActionPath($requestModule, $requestAction)
	{
		return sprintf(self::ACTION_PATH, $requestModule, $requestAction);
	}
	public static function getActionClass($requestModule, $requestAction)
	{
		return sprintf(self::ACTION_CLASS, ucfirst($requestModule), ucfirst($requestAction));
	}
	public static function getViewPath($requestModule, $requestAction)
	{
		return sprintf(self::VIEW_PATH, $requestModule, $requestAction);
	}
	public static function getViewClass($requestModule, $requestAction)
	{
		return sprintf(self::VIEW_CLASS, ucfirst($requestModule), ucfirst($requestAction));
	}
	public static function getTemplatePath($requestModule, $templateName)
	{
		return sprintf(self::TEMPLATE_PATH, $requestModule, $templateName);
	}
	public static function getGlobalTemplate($name)
	{
		return "template/$name.php";
	}
	public static function requireFile($file)
	{
		if(!file_exists($file))
		{
			throw new Exception(sprintf("Nem található a '%s' fájl.", $file));
		}
		require_once($file);
	}
	public static function redirect($module, $action, $params=array())
	{
		echo "<a href='".Request::getURL($module, $action, $params)."'>".$module."/".$action."</a>";
		die();
	}
}
		